using LF.Shared.Dtos.Input;
using LF.Shared.Dtos.Out;
using LF.Domain.Services;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.ObjectMapping;
using LF.Domain.Entities;
using LF.Application.Helpers;
using Microsoft.AspNetCore.Http;
using LF.Application.Extend;
using Microsoft.AspNetCore.Mvc;
using LF.Common;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Sys)]
    public class DictService : BaseService, IDictService
    {
        private readonly IDictManagerService _dictManager;
        private readonly IHttpContextAccessor _httpContext;

        public DictService(
            IObjectMapper<LFModule> mapper,
            IDictManagerService dictManager,
            IHttpContextAccessor httpContext,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _dictManager = dictManager;
            _httpContext = httpContext;
        }

        #region 字典类型管理
        /// <summary>
        /// 获取字典类型列表
        /// </summary>
        [LFAuthorize("获取字典类型列表", "system:dict-type:list")]
        public Result<DictTypeSearchOut> List(DictTypeSearch search)
        {
            var result = _dictManager.GetDictTypeList(search.Index, search.PageSize, search.Name, search.Code);
            var list = _mapper.Map<List<DictType>, List<DictTypeOut>>(result);
            var count = _dictManager.CountDictType(search.Name, search.Code);
            return Ok(new DictTypeSearchOut { Items = list, TotalCount = count });
        }

        /// <summary>
        /// 获取字典类型信息
        /// </summary>
        [LFAuthorize("查看字典类型", "system:dict-type:read")]
        public Result<DictTypeOut> Info(Guid id)
        {
            var dictType = _dictManager.GetDictType(id);
            var result = _mapper.Map<DictType, DictTypeOut>(dictType);
            return Ok(result);
        }

        /// <summary>
        /// 创建或更新字典类型
        /// </summary>
        [LFAuthorize("创建编辑字典类型", "system:dict-type:create")]
        public Result Edit(DictTypeOut dictType)
        {
            bool result;
            var model = _mapper.Map<DictTypeOut, DictType>(dictType);

            // 检查编码是否存在
            var existDictTypes = _dictManager.GetDictTypeList(1, 10, null, model.Code);
            var existDictType = existDictTypes.FirstOrDefault(d => d.Code == model.Code);
            if (existDictType != null && existDictType.Code == model.Code)
            {
                if (dictType.Id == null || dictType.Id != existDictType.Id)
                    return Error("字典编码已存在!");
            }

            if (dictType.Id == null)
            {
                model.Id = Guid.NewGuid();

                result = _dictManager.InsertDictType(model);
            }
            else
            {
                
                result = _dictManager.UpdateDictType(model);
            }

            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        /// <summary>
        /// 删除字典类型
        /// </summary>
        [LFAuthorize("删除字典类型", "system:dict-type:delete")]
        public Result Delete(Guid id)
        {
            if (_dictManager.DeleteDictType(id))
                return Ok();
            else
                return Error("删除失败!");
        }

        /// <summary>
        /// 获取所有字典类型
        /// </summary>
        [LFAuthorize("获取字典类型", "system:dict-type:list")]
        public Result<List<DictTypeOut>> GetAll()
        {
            var result = _dictManager.GetAllDictType();
            var list = _mapper.Map<List<DictType>, List<DictTypeOut>>(result);
            return Ok(list);
        }
        #endregion

        #region 字典项管理
        /// <summary>
        /// 获取字典项列表
        /// </summary>
        [LFAuthorize("获取字典项列表", "system:dict-item:list")]
        public Result<DictItemSearchOut> DictItemList(DictItemSearch search)
        {
            var result = _dictManager.GetDictItemList(search.Index, search.PageSize, search.TypeId, search.Label, search.Value);
            var list = _mapper.Map<List<DictItem>, List<DictItemOut>>(result);
            var count = _dictManager.CountDictItem(search.TypeId, search.Label, search.Value);
            return Ok(new DictItemSearchOut { Items = list, TotalCount = count });
        }

        /// <summary>
        /// 获取字典项信息
        /// </summary>
        [LFAuthorize("查看字典项", "system:dict-item:read")]
        public Result<DictItemOut> DictItemInfo(Guid id)
        {
            var dictItem = _dictManager.GetDictItem(id);
            var result = _mapper.Map<DictItem, DictItemOut>(dictItem);
            return Ok(result);
        }

        /// <summary>
        /// 创建或更新字典项
        /// </summary>
        [LFAuthorize("创建编辑字典项", "system:dict-item:create")]
        public Result DictItemEdit(DictItemOut dictItem)
        {
            bool result;
            var model = _mapper.Map<DictItemOut, DictItem>(dictItem);
            model.UpdateTime = DateTime.Now;

            // 检查同一字典类型下值是否重复
            var existDictItems = _dictManager.GetDictItemList(1, 10, model.TypeId, null, model.Value);
            var existDictItem = existDictItems.FirstOrDefault(d => d.Value == model.Value);
            if (existDictItem != null && existDictItem.Value == model.Value)
            {
                if (dictItem.Id == null || dictItem.Id != existDictItem.Id)
                    return Error("同一字典类型下字典值已存在!");
            }

            if (dictItem.Id == null)
            {
                model.Id = Guid.NewGuid();
             
                result = _dictManager.InsertDictItem(model);
            }
            else
            {
                
                result = _dictManager.UpdateDictItem(model);
            }

            if (result)
                return Ok();
            else
                return Error("保存失败!");
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        [LFAuthorize("删除字典项", "system:dict-item:delete")]
        public Result DictItemDelete(Guid id)
        {
            if (_dictManager.DeleteDictItem(id))
                return Ok();
            else
                return Error("删除失败!");
        }

        #endregion
    }
} 